const Controller = require('egg').Controller;

class CommonController extends Controller {

	async getFun () {

		const { ctx , app } = this;

		const { fun , pageNo, pageSize } = ctx.query;

		let sqlinfo = await app.redis.get('system').hget('dlq_sql', fun);

		// console.log('sqlinfo');
		// console.log(sqlinfo);

		if(sqlinfo == null){
			await ctx.service.common.sqlToRedis(fun);
			sqlinfo = await app.redis.get('system').hget('dlq_sql', fun);
		}

		const sqlobj = JSON.parse(sqlinfo);


		//解析sql，获取查询条件。然后重新组合sql。
		const sql_arr = sqlobj.sqlstr.split('where');

		//console.log(sql_arr);
		//查询主体
		let sql_before = sql_arr[0];


		//查询条件
		let sql_condition = '';
		let condition = ' ';
		let newKeys = [];
		let arr = [];
		//有条件
		if(sql_arr.length > 1){
			sql_condition = sql_arr[1];

			// console.log('sql_condition');
			// console.log(sql_condition);

			//解析所有的条件
			let reg = new RegExp(/\s(\S*)=\?/g);
			let paras = sql_condition.match(reg);

			let keys = [];
			paras.forEach(item => {
				keys.push(ctx.helper.trim(item).split('=?')[0]);
			})
			
			//通过传入的参数，去除其他的条件。
			//console.log(keys);
			keys.forEach((key, index) => {
				const t = ctx.query[key];
				if(t != undefined){
					newKeys.push(key);
					arr.push(t);
				}
			});

			//重新组装sql
			newKeys.forEach((key, index) => {
				if(index == newKeys.length - 1){
					condition += key + '=?';
				}else{
					condition += key + '=? and ';
				}
			});

			if(newKeys.length > 0){
				condition = ' where ' + condition;
			}

		}


		//条件后面的语句
		const sql_arr1 = sqlobj.sqlstr.split('=?');
		let sql_after = '';
		if(sql_arr1.length > 1){
			sql_after = sql_arr1[sql_arr1.length - 1];
		}

		const sql = sql_before + condition + sql_after
		//console.log(sql);

		//分页
		let sql_before_num = '';
		let pageSql = '';
		if(pageNo != undefined && pageSize != undefined){
			let before_arr = sql_before.split(' from ');
			sql_before_num = 'select count(1) as totalRecord from ' + before_arr[1];
			pageSql = sql_before_num + condition + sql_after;
		}

		const result = await ctx.service.common.getFun(sqlobj.dbname, sql, arr, pageSql, parseInt(pageSize), parseInt(pageNo));
		ctx.helper.success(result);
	}



	async setSqlToRedis () {

		const { ctx , app } = this;

		const name = ctx.query.name;

		console.log(name);

		const result = await ctx.service.common.sqlToRedis(name);


		console.log(result);

		ctx.helper.success(result);
	}



	async getTokenFromJuyou () {

		const { ctx , app } = this;

		console.log('getTokenFromJuyou');

		const { wxid } = ctx.query;

		const result = await ctx.curl('https://tsv.juyouhx.com/api/uc/wc/accountService/getToken', {
                method: 'GET',
                contentType: 'json',
                data: {
                    wxid,
                },
                dataType: 'json',
        });

        console.log(result);

        ctx.helper.success(result.data.data);

	}
    
}
module.exports = CommonController;